package com.tulele.vtool.task.async;

import com.tulele.vtool.model.*;
import com.tulele.vtool.model.combinedEntity.UserBrandCombinedInfo;
import com.tulele.vtool.service.*;
import com.tulele.vtool.utils.AliyunOssClientUtil;
import com.tulele.vtool.utils.DateUtil;
import com.tulele.vtool.utils.SysConstant;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Component
@Slf4j
public class UserAsyncTask {

    @Autowired
    private IUserImpressionInfoService userImpressionInfoService;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IVipInfoService vipInfoService;

    @Autowired
    private WantedUsersService wantedUsersService;

    @Autowired
    private IUserBrandInfoService userBrandInfoService;

    @Autowired
    private IUserPromotionSettleInfoService userPromotionSettleInfoService;

    @Autowired
    private IUserRelateArticleTypeInfoService iUserRelateArticleTypeInfoService;

    @Autowired
    private ArticleAsyncTask articleAsyncTask;

    @Autowired
    private UserGroupGzhService userGroupGzhService;

    /**
     * 设置用户默认印象
     * @param userId
     */
    @Async
    public void setUserDefaultImpression(Integer userId) {

        log.info("[enter setUserDefaultImpression] = " + userId);

//        userImpressionInfoService.addUserImpression(userId, "专业靠谱");
//
//        userImpressionInfoService.addUserImpression(userId, "值得信任");
//
//        userImpressionInfoService.addUserImpression(userId, "人超赞");

        //20200410,在用户新进来的时候，代替addUserImpression，不判断有没有，直接插
        try {
            userImpressionInfoService.newUserImpression(userId, "专业靠谱");

            userImpressionInfoService.newUserImpression(userId, "值得信任");

            userImpressionInfoService.newUserImpression(userId, "人超赞");
        } catch (Exception e) {

        }

        log.info("[end setUserDefaultImpression] = " + userId);
    }


    @Async
    public void updateUserInfo(WeixinServiceDL weixinService, WxMpOAuth2AccessToken wxMpOAuth2AccessToken, int finalUserId, SysGzh sysGzh){
        //log.error("执行updateUserInfo开始："+ DateUtil.getFormatDate("yyyy-MM-dd HH:mm:ss:SSS",DateUtil.getCurDate()));
        UserInfo userInfo = new UserInfo();

        try {

            WxMpUser wxMpUser = weixinService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);

            int userSubStatus = 0;
            WxMpUser userWxInfo = new WxMpUser();
            try {
                userWxInfo = weixinService.getUserService().userInfo(wxMpUser.getOpenId(), null);
                boolean userSubscribeStatus = userWxInfo.getSubscribe();
                if (userSubscribeStatus) {
                    userSubStatus = 1;
                }
            } catch (WxErrorException e) {
                e.printStackTrace();
            }

            userInfo.setUserId(finalUserId);
            userInfo.setWxUnionId(wxMpUser.getUnionId());
            userInfo.setNickName(wxMpUser.getNickname());
            userInfo.setUserName(wxMpUser.getNickname());
            userInfo.setAvatarUrl(AliyunOssClientUtil.uploadFileByFileUrl2(wxMpUser.getHeadImgUrl()));
            userInfo.setModifyTime(DateUtil.getCurDate());
            userInfo.setLastActiveTime(DateUtil.getCurDate());
            userInfo.setGzhId(sysGzh.getId());
            userInfo.setConcernStatus(userSubStatus); //20210126 添加更新关注状态
            if (userSubStatus == 1 && userWxInfo.getSubscribeTime() != null && userWxInfo.getSubscribeTime() > 0) {  //20210126
                userInfo.setSubscribeTime(DateUtil.timeStampToDate(userWxInfo.getSubscribeTime().toString()));
            }

            if (sysGzh.getOpenGroupCode() != null && sysGzh.getOpenGroupCode().trim().length() > 0) {
                userInfo.setOpenGroupCode(sysGzh.getOpenGroupCode());//开放平台分组标识
            }

            //20210423 处理vip状态 start
            UserVipValidInfo userVipValidInfoInDB = vipInfoService.getVipValidInfo(finalUserId);
            if (userVipValidInfoInDB != null
                    && userVipValidInfoInDB.getBeginTime() != null
                    && userVipValidInfoInDB.getEndTime() != null
                    && userVipValidInfoInDB.getBeginTime().getTime() < DateUtil.getCurDate().getTime()
                    && DateUtil.getCurDate().getTime() < userVipValidInfoInDB.getEndTime().getTime()) {//开始时间 和 结束时间 之内
                userInfo.setVipStatus(1);
            } else {
                userInfo.setVipStatus(0);//把vip关掉
            }
            //20210423 处理vip状态 end

            userInfoService.modifyWxUserInfo(userInfo);

            userGroupGzhService.updateLastActiveTimeAndPhoneModels(sysGzh.getGzhCode(),userInfo.getWxUnionId());
        } catch (Exception e) {
            log.error("[WechatHandler]_wxUserLogin_setVipState_error:" + e.getMessage());
        }

        try {
            //添加品牌

            int refererInDB = Optional.ofNullable(userInfoService.getUserReferer(finalUserId)).orElse(0);


            List<UserBrandCombinedInfo> userBrands = userBrandInfoService.getUserBrandInfo(userInfo.getUserId());

            if (userBrands == null || userBrands.size() <= 0) {//而且当前用户没有品牌
                if (refererInDB != 0) { //当推荐人不为空
                    List<UserBrandCombinedInfo> refererBrands = userBrandInfoService.getUserBrandInfo(refererInDB);//找推荐人的品牌

                    if (refererBrands != null && refererBrands.size() > 0) {
                        for (UserBrandCombinedInfo ubc : refererBrands) {
                            userBrandInfoService.subBrandInfo(finalUserId, ubc.getBrandId());

                        }
                    }
                }
            }


        } catch (Exception e) {
            log.error("[WechatHandler]_wxUserLogin_up_error:" + e.getMessage());
        }
        //log.error("执行updateUserInfo结束："+DateUtil.getFormatDate("yyyy-MM-dd HH:mm:ss:SSS",DateUtil.getCurDate()));
    }

    @Async
    public void createUserAttachInfo(WeixinServiceDL weixinService, WxMpOAuth2AccessToken wxMpOAuth2AccessToken, int finalUserId,String gzhCode) throws WxErrorException {
        //log.error("执行createUserAttachInfog开始：" + DateUtil.getFormatDate("yyyy-MM-dd HH:mm:ss:SSS", DateUtil.getCurDate()));

        // 获取用户微信账户信息
        WxMpUser wxMpUser = weixinService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(finalUserId);
        userInfo.setWxUnionId(wxMpUser.getUnionId());
        userInfo.setNickName(wxMpUser.getNickname());
        userInfo.setUserName(wxMpUser.getNickname());
        userInfo.setAvatarUrl(AliyunOssClientUtil.uploadFileByFileUrl2(wxMpUser.getHeadImgUrl()));//20210508

        userInfoService.modifyWxUserInfo(userInfo);

        userGroupGzhService.updateLastActiveTimeAndPhoneModels(gzhCode,userInfo.getWxUnionId());

        //默认添加3个印象
        this.setUserDefaultImpression(finalUserId);

        //默认添加3个文章关注类型
//        articleAsyncTask.setUserDefaultSubArticleType(finalUserId);

        //默认20%的等级
        UserPromotionSettleInfo userPromotionSettleInfo = new UserPromotionSettleInfo();
        userPromotionSettleInfo.setUserId(finalUserId);
        userPromotionSettleInfo.setFirstLevelProportion(20);

        if(gzhCode.equals("prodgjhkpt")) {//prodgjhkpt 共建获客平台 默认30%，hyl 20211201
            userPromotionSettleInfo.setFirstLevelProportion(30);
        }

        userPromotionSettleInfo.setCreateTime(new Date());
        userPromotionSettleInfoService.addPromotionSettleInfo(userPromotionSettleInfo);

        try {
            //如果有推荐人，默认关注推荐人的品牌
            int refererInDB = Optional.ofNullable(userInfoService.getUserReferer(finalUserId)).orElse(0);
            boolean setUserBrand = false;
            boolean setUserType = false;
            if (refererInDB != 0) {
                List<UserBrandCombinedInfo> userBrands = userBrandInfoService.getUserBrandInfo(refererInDB);
                if (userBrands != null && userBrands.size() > 0) {
                    for (UserBrandCombinedInfo ubc : userBrands) {
                        userBrandInfoService.subBrandInfo(finalUserId, ubc.getBrandId());
                    }
                    setUserBrand = true;
                }
            }

            if (!setUserType) {
                // 关注推荐人的类型 2022-03-26
                UserRelateArticleTypeInfo userRelateArticleTypeInfo = null;
                if (refererInDB != 0) {
                    userRelateArticleTypeInfo = iUserRelateArticleTypeInfoService.getUserRelateArticleTypeInfo(Integer.valueOf(refererInDB));
                }

                if (userRelateArticleTypeInfo != null) {
                    String articleTypeIds = userRelateArticleTypeInfo.getArticleTypeIds();
                    iUserRelateArticleTypeInfoService.recordUserRelateArticleTypeInfo(finalUserId, articleTypeIds);
                } else {
                    iUserRelateArticleTypeInfoService.recordUserRelateArticleTypeInfo(finalUserId, SysConstant.DEFAULT_SUBSCRIBE_ARTICLE_TYPE);// 财税、正能量、健康养生
                }
            }

        } catch (Exception e) {
            log.error("[WechatHandler]_wxUserLogin_down_error:" + e.getMessage());
        }
        //log.error("执行createUserAttachInfog结束：" + DateUtil.getFormatDate("yyyy-MM-dd HH:mm:ss:SSS", DateUtil.getCurDate()));
    }

    @Async
    public void checkBlock(WeixinServiceDL weixinService, WxMpOAuth2AccessToken wxMpOAuth2AccessToken,int finalUserId) throws Exception {
        // 获取用户微信账户信息
        WxMpUser wxMpUser = weixinService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
        boolean r = wantedUsersService.checkAvatar(finalUserId, wxMpUser.getNickname());
        if (r) {
            userInfoService.setBlockState(finalUserId);
        }
    }

}
